#!/usr/bin/env python3
"""
设备配置管理器启动脚本
专门用于启动设备配置管理系统
"""

import sys
import os
import logging
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

def main():
    try:
        print("🚀 启动设备配置管理系统...")
        print("=" * 50)
        
        # 检查环境
        print(f"✅ Python 版本: {sys.version.split()[0]}")
        print(f"📁 项目路径: {project_root}")
        
        # 检查虚拟环境
        if hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix):
            print("✅ 虚拟环境已激活")
        else:
            print("⚠️  未检测到虚拟环境")
            print("建议激活虚拟环境: .\\iot-collector-env\\Scripts\\Activate.ps1")
        
        print("=" * 50)
        
        # 导入依赖模块
        try:
            from web.app import create_app
            from services.storage import StorageService
            from services.alarm import AlarmService
            from services.scheduler import SchedulerService
            from services.config_manager import ConfigManager
            from core.engine import DataEngine
            print("✅ 模块导入成功")
        except ImportError as e:
            print(f"❌ 模块导入失败: {e}")
            print("请确保已安装所有依赖: pip install -r requirements.txt")
            return
        
        # 创建基本配置
        config = {
            'sqlite': {'enabled': True, 'path': 'data/iot_collector.db'},
            'influxdb': {'enabled': False},
            'mysql': {'enabled': False}
        }

        # 初始化服务
        print("🔧 初始化服务组件...")
        storage = StorageService(config)
        alarm = AlarmService({})
        scheduler = SchedulerService()
        engine = DataEngine(storage, alarm)
        
        # 初始化配置管理器
        config_manager = ConfigManager()
        
        print("✅ 服务初始化成功")
        
        # 创建Flask应用
        app = create_app(engine, storage, alarm, scheduler, {
            'DEBUG': True,
            'HOST': '127.0.0.1',
            'PORT': 5000
        })
        
        print("\n🌐 Web服务器启动中...")
        print("📊 访问地址:")
        print("   设备管理: http://127.0.0.1:5000/device-manager")
        print("   主页: http://127.0.0.1:5000/")
        print("   仪表盘: http://127.0.0.1:5000/dashboard")
        print("   状态测试: http://127.0.0.1:5000/status-test")
        print("\n🔧 API端点:")
        print("   设备配置: GET/POST /api/devices/config")
        print("   配置验证: POST /api/devices/config/validate")
        print("   连接测试: POST /api/device/test-connection")
        print("   备份管理: GET /api/devices/config/backup")
        print("\n💡 按 Ctrl+C 停止服务器")
        print("=" * 50)
        
        # 启动服务器
        app.run(
            host='127.0.0.1',
            port=5000,
            debug=True,
            use_reloader=False
        )
        
    except KeyboardInterrupt:
        print("\n🛑 服务器已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        import traceback
        traceback.print_exc()
        print("\n💡 故障排除建议:")
        print("1. 检查是否在项目根目录下运行")
        print("2. 确认虚拟环境已激活")
        print("3. 检查依赖是否已安装: pip install -r requirements.txt")
        print("4. 查看完整错误信息进行排查")

if __name__ == '__main__':
    main() 